package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet("/addUser")
public class AddUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取表单数据
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String lans = request.getParameter("lans");

        try {
            // 加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 连接数据库
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/FinalTest", "root", "123456");

            // 检查用户名是否已存在
            PreparedStatement checkStmt = conn.prepareStatement("SELECT * FROM user WHERE id = ?");
            checkStmt.setString(1, id);
            ResultSet rs = checkStmt.executeQuery();

            if (rs.next()) {
                // 用户名已存在，设置错误信息并转发回添加页面
                request.setAttribute("errorMessage", "用户名已存在，请选择其他用户名！");
                request.getRequestDispatcher("addUser.jsp").forward(request, response);
            } else {
                // 用户名不存在，插入新用户
                PreparedStatement ps = conn.prepareStatement("INSERT INTO user (id, name, password, email, gender, birthday, lans) VALUES (?, ?, ?, ?, ?, ?, ?)");
                ps.setString(1, id);
                ps.setString(2, name);
                ps.setString(3, password);
                ps.setString(4, email);
                ps.setString(5, gender);
                ps.setDate(6, Date.valueOf(birthday));
                ps.setString(7, lans);
                ps.executeUpdate();

                // 添加成功，跳转到用户列表页面
                response.sendRedirect("userList.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 发生异常，设置错误信息并转发回添加页面
            request.setAttribute("errorMessage", "添加用户失败，请稍后重试！");
            request.getRequestDispatcher("addUser.jsp").forward(request, response);
        }
    }
}